import processing.serial.*;



Serial myPort;//The serial port

PFont f;

float filter, eps;

int byte1, byte2, byte3, byte4;


int getData() {

  boolean done;

  int low, high, value;

  done =false;

  byte2 = 0;

  byte3 = 0;

  byte4 = 0;

  myPort.clear();

  while (!done) {

    if (myPort.available() > 1) {

      byte1 = byte2;

      byte2 = byte3;

      byte3 = byte4;

      byte4 = (int)myPort.read();

      if ((byte1 == 2) & (byte2 ==3) & (byte3 ==4) &(byte4 == 5))

        done =true;

    }

  }

  while (myPort.available () < 1);

  low = myPort.read();

  while (myPort.available () < 1);

  high = myPort.read();

  value = 256*high + low;

  if (value > 511) value = value - 1024;

  println("low: " + low +",high: " + high + ",val: " + value);

  return value;

}


void setup() {

  size(700, 500, P3D);

  background(0);

  noStroke();

  f = createFont("Arial" ,30, true);

  println(Serial.list());

  //Open the port you are using at the rate you want:

  myPort =new Serial(this, Serial.list()[1], 9600);

  eps = 0.5;// filter time constant

  filter = 0.0;// filtered value

}


void draw() {

  size(700, 500, OPENGL);

  background(0);

  noStroke();

  lights();

  textFont(f,30);

  fill(240, 255);

  text("Temperature Change" ,200,100);

  //translate(0, 0, -50);

  float aNum=0;

  float V, R, B, R25, T;

  boolean done;

  int value;

  value = getData();

  V = 2.5 - value*5.0/(20.0*512.0);

  R = 10000.0/(5.0/V-1.0);

  // NHQ103B375R5

  // R25 10000 (0)

  // B (25/85) 3750 (K)

  // R(T9C)) = R(25)*exp(B*(1/(T(C)+273.15)-(1/(25+273.15))))

  B = 3750.0;

  R25 = 10000.0;

  T = 1.0/(log(R/R25)/B+(1/(25.0+273.15))) - 273.15;

  filter = (1-eps)*filter +eps*T;

  println("filter: " + filter);

  translate(width/2+30, height/2, 0);

  rotateX(-PI/6);

  rotateY(PI/3 + 210/float(height) * PI);

  box(45, (filter-20)*20, 45);

 

}


/*

eps = 0.5 # filter time constant

 filter = 0.0 # filtered value

 

 global filter, eps

 #

 # idle routine

 #

 byte2 = 0 

 byte3 = 0

 byte4 = 0

 ser.flush()

 while 1:

 #

 # find framing

 #

 byte1 = byte2

 byte2 = byte3

 byte3 = byte4

 byte4 = ord(ser.read())

 if ((byte1 ==1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)):

 break

 low = ord(ser.read())

 high = ord(ser.read())

 value = 256*high + low

 if (value > 511):

 value -= 1024

 V = 2.5 - value*5.0/(20.0*512.0)

 R = 10000.0/(5.0/V-1.0)

 # NHQ103B375R5

 # R25 10000 (0)

 # B (25/85) 3750 (K)

 #R(T(C)) = R(25)*exp(B*(1/(T(C)+273.15)-(1/(25+273.15))))

 B = 3750.0

 R25 = 10000.0

 T = 1.0/(LOG(R/R25)/B+(1/(25.0+273.15))) - 273.15

 filter = (1-eps)*filter + eps*T

 x = int(.2*WINDOW + (.9-.2)*WINDOW*(FILTER-20.0)/10.0)

 canvas.itemconfigure("text",text="%.2f"%filter)

 canvas.coords('rect1',.2*WINDOW,.05*WINDOW,x,.2*WINDOW)

 canvas.coords('rect2',x,.05*WINDOW,.9*WINDOW,.2*WINDOW)

 canvas.update()

 parent.after_idle(idle,parent,canvas)

 */